package com.wolfheader.wolfgame.controller;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wolfheader.wolfgame.dao.admin.GameDao;
import com.wolfheader.wolfgame.dao.admin.GamePlayerDao;
import com.wolfheader.wolfgame.dao.admin.GameRecordDao;
import com.wolfheader.wolfgame.entity.GamePlayerEntity;
import com.wolfheader.wolfgame.entity.GameRecordEntity;
import com.wolfheader.wolfgame.entity.admin.GameEntity;
import com.wolfheader.wolfgame.service.GamePlayerService;
import com.wolfheader.wolfgame.service.GameRecordService;
import com.wolfheader.wolfgame.service.admin.GameService;
import com.wolfheader.wolfgame.util.CheckUtils;
import com.wolfheader.wolfgame.util.HttpClientUtil;
import com.wolfheader.wolfgame.util.JsonBinder;
import com.wolfheader.wolfgame.weixin.WeiXinUtils;
import com.wolfheader.wolfgame.weixin.WeixinSignElem;

import net.sf.json.JSONObject;

/**
 * Controller - 游戏
 * 
 * @author LMC
 * @version 1.0
 */
@Controller("gameController")
@RequestMapping("/game")
public class GameController {

	public static final String appid = "wxf03432cd145651e6";

	public static final String appsecret = "d5da3da3d40578ece61e23a82aa6cabf";

	public static final String game_server = "http://www.wolfheader.com/";// "http://5306bb23.nat123.net/";

	@Resource(name = "gameServiceImpl")
	private GameService gameService;

	@Autowired
	private GameDao gameDao;

	@Resource(name = "gamePlayerServiceImpl")
	private GamePlayerService gamePlayerService;

	@Resource(name = "gameRecordServiceImpl")
	private GameRecordService gameRecordService;

	@Autowired
	private GamePlayerDao gamePlayerDao;

	@Autowired
	private GameRecordDao gameRecordDao;

	/**
	 * 游戏走的入口
	 * 
	 * @param request
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(HttpServletRequest request, ModelMap model) throws Exception {
		String gameId = request.getParameter("id");
		if (StringUtils.isBlank(gameId)) {
			gameId = request.getParameter("gameid");
		}
		String hid = "";
		if (request.getParameter("hid") != null) {
			hid = request.getParameter("hid");
		}
		GameEntity game = gameDao.findOne(Long.parseLong(gameId));
		if (game == null) {
			return null;
		}
		String path = game.getGamePath();
		if (StringUtils.isBlank(path)) {
			return null;
		}
		String webPath = game_server + "game/startWeixinInfo";
		String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&state=STATE&scope=SCOPE#wechat_redirect";
		String finalUrl = authUrl.replace("APPID", appid).replace("REDIRECT_URI", URLEncoder.encode(webPath, "utf-8"))
				.replace("SCOPE", "snsapi_userinfo").replace("STATE", gameId + ":" + hid);
		return "redirect:" + finalUrl;
	}

	/**
	 * 授权微信回调，获取用户基本信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */

	@SuppressWarnings({ "unchecked", "null" })
	@RequestMapping(value = "/startWeixinInfo", method = RequestMethod.GET)
	public String startWeixinInfo(HttpServletRequest request, ModelMap model) throws Exception {
		String state = request.getParameter("state");
		if (StringUtils.isBlank(state)) {
			return null;
		}
		String[] stateArr = state.split(":");
		String gameId = stateArr[0];
		String hid = "";
		if (stateArr.length > 1) {
			hid = stateArr[1];
		}
		String code = request.getParameter("code");
		GameEntity game = gameDao.findOne(Long.parseLong(gameId));
		// 游戏不存在并且 游戏没有游戏路径
		if (game == null && StringUtils.isBlank(game.getGamePath())) {
			return null;
		}
		if (StringUtils.isNotBlank(code)) {
			// 第二步获取网页access_token
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
			String param = "appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
			String getParam = param.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
			JSONObject obj = JSONObject.fromObject(HttpClientUtil.sendGet(url, getParam));
			HashMap<String, String> map = (HashMap<String, String>) JSONObject.toBean(obj, HashMap.class);
			// qi
			try {
				// 第三步获取用户信息
				String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo";
				String userInfoParam = "access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
				String getUserInfoParam = userInfoParam.replace("ACCESS_TOKEN", map.get("access_token"))
						.replace("OPENID", map.get("openid"));
				JSONObject userInfo = JSONObject.fromObject(HttpClientUtil.sendPost(userInfoUrl, getUserInfoParam));
				HashMap<String, Object> userInfoMap = (HashMap<String, Object>) JSONObject.toBean(userInfo,
						HashMap.class);
				GamePlayerEntity entity = gamePlayerService.editGamePlayer(userInfoMap);
				GameRecordEntity record = gameRecordDao.findPlayerByOpenidAndGameid(entity.getOpenid(), gameId);
				// 新增
				if (record == null) {
					gameRecordService.createNewCord(entity, gameId);
				}
				String redirectUrl = game.getGamePath() + "#?" + "timestamp=" + new Date().getTime() + "&gameid="
						+ gameId + "&openid=" + userInfoMap.get("openid") + "&hid=" + hid;
				return "redirect:" + redirectUrl;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@CrossOrigin
	@RequestMapping(value = "/isrun", method = RequestMethod.POST)
	public @ResponseBody String isrun(HttpServletRequest request) {
		String gameId = request.getParameter("gameid");
		// 如果是个合法的能转换的数字
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(gameId) && NumberUtils.isDigits(gameId)) {
			GameEntity game = gameDao.findOne(Long.parseLong(gameId));
			if (game == null) {
				map.put("status", "0");
				map.put("msg", "游戏不存在");
				return JsonBinder.toJson(map);
			}
			map = (Map<String, Object>) gameService.checkGameOutTime(game, "0");
		} else {
			map.put("status", "0");
			map.put("msg", "参数错误");
		}
		return JsonBinder.toJson(map);
	}

	/**
	 * 获取排行榜
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/rank", method = RequestMethod.POST)
	public @ResponseBody String rank(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String gameid = request.getParameter("gameid");
		String openid = request.getParameter("openid");
		if (!CheckUtils.checkGameIdIsTrue(gameid) || StringUtils.isBlank(openid)) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}
		List<GameRecordEntity> list = gameRecordService.findListByGameId(gameid);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setRank(i);
		}
		map.put("all", list);
		GameRecordEntity mine = gameRecordDao.findPlayerByOpenidAndGameid(openid, gameid);
		if (mine == null) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}

		mine.setRank(gameRecordDao.computeMyRank(gameid, mine.getTotalScore(), mine.getRecordDateTime()));
		map.put("myall", mine);
		return JsonBinder.toJson(map);
	}

	/**
	 * 微信分享借口
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/share", method = RequestMethod.POST)
	public @ResponseBody String weixinConfig(HttpServletRequest request, ModelMap model) {
		String gameid = request.getParameter("gameid");
		String openid = request.getParameter("openid");
		String url = request.getParameter("url");
		WeixinSignElem elem = WeiXinUtils.sign(url);
		String shareUrl = game_server + "/game/index#?gameid=" + gameid + "&hid=" + openid;
		elem.setUrl(shareUrl);
		return JsonBinder.toJson(elem);
	}

	/**
	 * 获取用户玩家信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/getPlayerData", method = RequestMethod.POST)
	public @ResponseBody String getPlayerData(HttpServletRequest request, ModelMap model) {
		String openid = request.getParameter("openid");
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(openid)) {
			GamePlayerEntity entity = gamePlayerDao.findByOpenid(openid);
			if (entity != null) {
				map.put("openid", entity.getOpenid());
				map.put("nickname", entity.getNickname());
				map.put("phone", entity.getPhone());
				map.put("avatar", entity.getAvatar());
				map.put("address", entity.getAddress());
				map.put("realname", entity.getRealname());
			}
		} else {
			map.put("status", "0");
			map.put("msg", "参数错误");
		}
		return JsonBinder.toJson(map);
	}

	@CrossOrigin
	@RequestMapping(value = "/score", method = RequestMethod.POST)
	public @ResponseBody String score(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String gameid = request.getParameter("gameid");
		String openid = request.getParameter("openid");
		String score = request.getParameter("score");
		// 参数必须存在
		if (!CheckUtils.checkGameIdIsTrue(gameid) || !StringUtils.isNotBlank(openid)
				|| !CheckUtils.checkGameIdIsTrue(score)) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}
		if (gameRecordService.saveScore(gameid, openid, Integer.parseInt(score))) {
			map.put("status", "1");
			GameRecordEntity record = gameRecordDao.findPlayerByOpenidAndGameid(openid, gameid);
			Integer rank = gameRecordDao.computeMyRank(gameid, record.getTotalScore(), record.getRecordDateTime());
			map.put("rank", rank);
			System.out.println("rank = " + rank);
		} else {
			map.put("status", "0");
			map.put("msg", "参数错误");
		}

		return JsonBinder.toJson(map);
	}

	/**
	 * 好友助力
	 * 
	 * @param request
	 * @return
	 */
	@CrossOrigin
	@RequestMapping(value = "/assScore", method = RequestMethod.POST)
	public @ResponseBody String assScore(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String gameid = request.getParameter("gameid");
		String openid = request.getParameter("openid");
		String score = request.getParameter("score");
		String hid = request.getParameter("hid");
		if (!CheckUtils.checkGameIdIsTrue(gameid) || !CheckUtils.checkGameIdIsTrue(score) || StringUtils.isBlank(hid)
				|| StringUtils.isBlank(openid)) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}
		if (openid.equals(hid)) {
			map.put("status", 0);
			map.put("msg", "不能助力自己");
			return JsonBinder.toJson(map);
		}
		GameEntity game = gameDao.findOne(Long.parseLong(gameid));
		if (game == null) {
			map.put("status", 0);
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}
		// 判断是否在时间内
		Boolean flag = (Boolean) gameService.checkGameOutTime(game, "1");
		if (!flag) {
			map.put("status", "0");
			map.put("msg", "gametime err");
			return JsonBinder.toJson(map);
		}
		;
		// 超过设定的最大分数
		if (game.getMaxScore() > 0 && game.getMaxScore() < Integer.parseInt(score)) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}

		GameRecordEntity record = gameRecordDao.findPlayerByOpenidAndGameid(hid, gameid);
		if (record == null) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return JsonBinder.toJson(map);
		}

		// 当前的助力次数大于了最大助力次数
		if (record.getAssCount() > 0 && record.getAssCount() >= game.getMaxAssCount()) {
			map.put("status", "0");
			map.put("msg", "超过最大助力次数");
			return JsonBinder.toJson(map);
		}
		record.setAssCount(record.getAssCount() + 1);
		record.setAssScore(record.getAssScore() + Integer.parseInt(score));
		record.setTotalScore(record.getScore() + record.getAssScore());
		record.setRecordDateTime(new Date().getTime());
		gameRecordDao.save(record);
		map.put("status", "1");
		return JsonBinder.toJson(map);
	}

	/**
	 * 更新玩家信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updatePlayer", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> updatePlayer(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String openid = request.getParameter("openid");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		String realname = request.getParameter("realname");
		String taobaoid = request.getParameter("taobaoId");
		if (StringUtils.isBlank(openid) || StringUtils.isBlank(phone)) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return map;
		}

		GamePlayerEntity player = gamePlayerDao.findByOpenid(openid);
		if (player == null) {
			map.put("status", "0");
			map.put("msg", "参数错误");
			return map;
		}
		player.setAddress(address);
		player.setRealname(realname);
		player.setPhone(phone);
		// player.setTaobaoId(taobaoid);
		gamePlayerDao.save(player);
		map.put("status", "1");
		return map;
	}

}
